package com.sp.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.sp.app.domain.Course;
import com.sp.app.domain.Coursecomment;
import com.sp.app.domain.Curelation;
import com.sp.app.domain.User;
import com.sp.app.service.CourseService;
import com.sp.app.service.CoursecommentService;
import com.sp.app.service.CurelationService;
import com.sp.app.util.DateUtil;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/Course")
public class CourseController {

    @Autowired
    private CourseService courseService;
    @Autowired
    private CurelationService curelationService;


    @Autowired
    private CoursecommentService coursecommentService;

    @ResponseBody
    @RequestMapping("/queryOneCom")
    public String queryOneCom(String ID){
        Coursecomment course = new Coursecomment();
        course.setId(ID);
        System.out.println("===================================="+ID);
        List<Coursecomment> list = coursecommentService.queryAll(course);
        course = list.get(0);
        JSONObject json = new JSONObject();
        return json.toJSONString(course);
    }



    @RequestMapping("addComment")
    public String addComment(HttpServletRequest request, Coursecomment coursecomment){
        User user = (User) request.getSession().getAttribute("user");
        coursecomment.setCreatetime(DateUtil.getStringToday());
        coursecomment.setUserid(user.getName());
        coursecomment.setId(String.valueOf(Math.random()).substring(2,10));
        coursecommentService.insert(coursecomment);
        return "redirect:/Course/suggeetion";
    }


    @ResponseBody
    @RequestMapping("jsoncourse")
    public String jsoncourse(HttpServletRequest request, Curelation course){
        User user = (User) request.getSession().getAttribute("user");
        /*String type = "1";

        if ("1".equals(user.getType())){
            type="2";
        }
        course.setType(type);
        course.setUserid(user.getId());*/
        List<Curelation> curelationList = curelationService.queryAll(course);
        List<Course> dataList = new ArrayList<>();
        for (int i = 0; i < curelationList.size(); i++) {
            Course curelation = courseService.selectByPrimaryKey(curelationList.get(i).getCourseid());
            dataList.add(curelation);
        }

        JSONObject json = new JSONObject();
        return json.toJSONString(dataList);
    }

    @RequestMapping("suggeetion")
    public String suggeetion(HttpServletRequest request, Coursecomment coursecomment){

        List<Coursecomment> coursecomments = coursecommentService.queryAll(coursecomment);


        request.setAttribute("list",coursecomments);
        return "suggeetion";
    }

    @RequestMapping("view")
    public String view(HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("user");

        String type = "1";

        if ("1".equals(user.getType())){
            type="2";
        }

        List<Map<String,String>> list=curelationService.courseview(type,user.getId());
        request.setAttribute("list",list);
        return "courseview";
    }

    @RequestMapping("deletecomment")
    public String deletecomment(String ID){
        coursecommentService.deleteByPrimaryKey(ID);
        return "redirect:/Course/suggeetion";
    }



    @RequestMapping("queryAll")
    public String queryAll(HttpServletRequest request, Course course){
        List<Course> list = courseService.queryAll(course);
        request.setAttribute("list",list);

        return "course";
    }

    @RequestMapping("/receive")
    public String receive(HttpServletRequest request, HttpServletResponse response, MultipartFile file){

        try {
            //也可以用request获取上传文件
            //MultipartFile  fileFile = request.getFile("file"); //这里是页面的name属性
            //转换成输入流
            InputStream is = file.getInputStream();
            //得到excel
            Workbook workbook = Workbook.getWorkbook(is);
            //得到sheet
            Sheet sheet = workbook.getSheet(0);
            //得到列数
            int colsNum = sheet.getColumns();
            //得到行数
            int rowsNum = sheet.getRows();
            //单元格
            Cell cell;
            Cell cell1;

            List<Map> list = new ArrayList<>();
            Map<Integer, String> map = new HashMap<Integer, String>();
            for (int i = 1; i < rowsNum; i++) {//我的excel第一行是标题,所以 i从1开始
                cell  = sheet.getCell(0,i);
                cell1 = sheet.getCell(5,i);
                Curelation curelation = new Curelation();

                curelation.setId(cell.getContents());
                curelation.setScore(cell1.getContents());
                curelationService.updateByPrimaryKey(curelation);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (BiffException e) {
            e.printStackTrace();
        }
        return "redirect:/Course/queryCourse";
    }

    @RequestMapping("/queryCourse")
    public String queryScore(HttpServletRequest request,Curelation curelation){

        curelation.setType("1");
        List<Curelation> list = curelationService.queryAll(curelation);
        request.setAttribute("list",list );
        return "ScoreList";
    }

    @RequestMapping("/teacher")
    public String teacher(HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("user");
        Course course = new Course();
        course.setCourseteacher(user.getName());
        List<Course> courseList = courseService.queryAll(course);
        request.setAttribute("list",courseList);
        return "teacherDeal";
    }

    @RequestMapping("/student")
    public String student(HttpServletRequest request){
        Course course = new Course();
        course.setStatus("1");
        List<Course> courseList = courseService.queryAll(course);
        request.setAttribute("list",courseList);
        return "studentChoose";
    }


    @RequestMapping("/upload")
    public  String upload(){

        return "uploadScore";
    }


    @RequestMapping("/Export")
    public void Export(HttpServletResponse response, User user){

        response.setContentType("application/binary;charset=UTF-8");
        try {
            ServletOutputStream out = response.getOutputStream();
            String fileName1 = "学生信息";
            String fileName2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
            String fileName = fileName1+fileName2;
            response.setHeader("Content-disposition", "attachment; filename=" +new String(fileName.getBytes("gbk"),"iso8859-1") + ".xls");
            String[] titles = { "成绩编号","学生编号", "学生姓名", "课程编号", "课程名称", "成绩" };
            courseService.export(titles, out,user);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    @RequestMapping("delete")
    public String delete(String ID){
        courseService.deleteByPrimaryKey(ID);
        return "redirect:/Course/queryAll";
    }

    @RequestMapping("update")
    public String update(Course course){
        courseService.updateByPrimaryKey(course);
        return "redirect:/Course/queryAll";
    }

    @Transactional
    @RequestMapping("update1")
    public String update1(HttpServletRequest request,Course course){
        course.setStatus("1");
        courseService.updateByPrimaryKey(course);
        User user = (User) request.getSession().getAttribute("user");
        Curelation curelation1 = new Curelation();
        curelation1.setCourseid(course.getId());
        curelation1.setUserid(user.getId());
        List<Curelation> curelationList = curelationService.queryAll(curelation1);
        if(curelationList.size()==0){
            Curelation curelation = new Curelation();
            curelation.setUserid(user.getId());
            curelation.setCourseid(course.getId());
            curelation.setId(String.valueOf(Math.random()).substring(2, 10));
            curelation.setType("2");
            curelationService.insert(curelation);
        }
        return "redirect:/Course/teacher";
    }

    @RequestMapping("update2")
    public String update2(HttpServletRequest request,Course course){
        User user = (User) request.getSession().getAttribute("user");
        Curelation curelation = new Curelation();
        curelation.setUserid(user.getId());
        curelation.setCourseid(course.getId());
        List<Curelation> curelationList = curelationService.queryAll(curelation);
        if(curelationList.size() == 0){
            curelation.setId(String.valueOf(Math.random()).substring(2, 10));
            curelation.setType("1");
            curelationService.insert(curelation);
        }else{
            Curelation curelation1 = curelationList.get(0);
            curelation1.setUserid(user.getId());
            curelation1.setCourseid(course.getId());
            System.out.println(curelation1.toString());
            curelationService.updateByPrimaryKey(curelation1);
        }
        return "redirect:/Course/student";
    }

    @ResponseBody
    @RequestMapping("/queryOne")
    public String queryOne(String ID){
        Course course = new Course();
        course.setId(ID);
        List<Course> list = courseService.queryAll(course);
        course = list.get(0);
        JSONObject json = new JSONObject();
        return json.toJSONString(course);
    }

    @RequestMapping("add")
    public String addCourse(Course course){
        course.setId(String.valueOf(Math.random()).substring(2, 10));
        System.out.println(course.toString());
        courseService.insert(course);
        return "redirect:/Course/queryAll";
    }

}
